<template>
  <el-form
    :model="formData"
    ref="formRef"
    @submit.prevent
    :rules="formRules"
    label-width="130px"
    :disabled="mode === 'view'"
    :validate-on-rule-change="false"
  >
    <el-row>
      <el-col :span="12">
        <el-form-item label="姓名" prop="name">
          <el-select
            v-model="formData.name"
            filterable
            clearable
            remote
            placeholder="请输入姓名搜索"
            :remote-method="querySearchAsync"
            value-key="id"
            @change="handleSelect"
          >
            <el-option
              id="default-option"
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item"
            ></el-option>
          </el-select> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="用户名" prop="userName">
          <el-select
            v-model="formData.userName"
            filterable
            clearable
            remote
            placeholder="请选择"
            :remote-method="querySearchAsync"
            value-key="id"
          >
            <el-option
              id="default-option"
              v-for="item in userList"
              :key="item.id"
              :label="item.userName"
              :value="item.userName"
            ></el-option>
          </el-select> </el-form-item
      ></el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="邮箱" prop="email">
          <el-input
            placeholder="选择用户名后自动带出"
            disabled
            type="email"
            v-model="formData.email"
            class="width-custom"
          ></el-input> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="手机号" prop="phoneNum">
          <el-input
            placeholder="选择用户名后自动带出"
            disabled
            oninput="value=value.replace(/[^\d]/g,'')"
            v-model.number.trim="formData.phoneNum"
            class="width-custom"
          ></el-input> </el-form-item
      ></el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="性别" prop="sex">
          <el-select
            v-model="formData.sex"
            clearable
            placeholder="选择用户名后自动带出"
          >
            <el-option label="女" value="0"></el-option>
            <el-option label="男" value="1"></el-option>
          </el-select> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="所属单位部门" prop="companyName">
          <el-input
            disabled
            v-model="formData.companyName"
            class="width-custom"
            autocomplete="off"
            placeholder="选择用户名后自动带出"
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="科技人才类别" prop="kcMemberName">
          <el-select
            style="width: 100%"
            v-model="formData.kcMemberName"
            clearable
            placeholder="请选择"
          >
            <el-option label="基础研究人员" value="基础研究人员"></el-option>
            <el-option
              label="科技研发人员-科研项目管理人员"
              value="科技研发人员-科研项目管理人员"
            ></el-option>
            <el-option
              label="科技研发人员-研究和技术人员"
              value="科技研发人员-研究和技术人员"
            ></el-option>
            <el-option label="科技管理人员" value="科技管理人员"></el-option>
            <el-option
              label="科技直接服务人员"
              value="科技直接服务人员"
            ></el-option>
          </el-select> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="职务/职位" prop="position">
          <el-input
            placeholder="请输入"
            class="width-custom"
            v-model="formData.position"
          ></el-input> </el-form-item
      ></el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="荣誉/称号" prop="honorTitle">
          <el-input
            type="textarea"
            class="width-custom"
            placeholder="请输入内容"
            :rows="3"
            v-model="formData.honorTitle"
          ></el-input> </el-form-item
      ></el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            v-model="formData.remark"
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <el-row justify="end" v-if="mode !== 'view'">
    <el-button @click="handleSubmit(false)">取 消</el-button>
    <el-button type="primary" :loading="btnloading" @click="handleSubmit(true)">
      确 定
    </el-button>
  </el-row>
</template>

<script lang="ts">
import {
  PropType,
  defineComponent,
  onMounted,
  reactive,
  ref,
  toRef,
  toRefs
} from "vue";
import { postDictList } from "/@/api/common";
import { postSysCompanyList } from "/@/api/organization";
import { roleList } from "/@/api/roles";
import {
  addUser,
  getUsersForScience,
  postScienceUserInfo,
  updateScienceUser
} from "/@/api/user";
import NotifMessage from "/@/utils/message/notification";

import { cloneDeep } from "lodash-es";

import { ModeType, RoleListType, UserInfoType, userTypeEnum } from "../types";

export default defineComponent({
  name: "UserDetail",
  props: {
    mode: {
      type: String as PropType<ModeType>,
      require: true,
      default: "add"
    },
    userInfo: {
      type: Object as PropType<UserInfoType>,
      default: () => {}
    },
    companyInfo: {
      type: Object,
      default: () => {}
    }
  },
  emits: ["emitClose"],
  setup(props, { emit }) {
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const currentInfo = toRef(props, "userInfo");

    let userTypeList = ref([]);
    let roleLists = ref<RoleListType[]>([]);
    let companyLists = ref([]);
    let userList = ref([]);
    let principalCompanyArr = ref([]);
    let state = reactive({
      formData: {
        name: "",
        userName: "",
        email: "",
        phoneNum: "",
        sex: null,
        companyName: "",
        kcMemberName: "",
        position: "",
        honorTitle: "",
        remark: "",
        userId: null
      },
      btnloading: false // 按钮加载
    });

    const formRules = {
      name: [{ required: true, message: "请输入姓名", trigger: "change" }],
      userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
      phoneNum: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      companyName: [
        { required: true, message: "请输入所属单位部门", trigger: "blur" }
      ],
      kcMemberName: [
        { required: true, message: "请选择科技人员类别", trigger: "change" }
      ],
      position: [
        { required: true, message: "请输入职务/职位", trigger: "blur" }
      ]
    };
    let deptList = ref([]);
    const initPrincipalCompanyList = async () => {
      try {
        const params = {
          dicType: "rd_principal_cmpy"
        };
        const { code, data } = await postDictList(params);
        if (code === 200) {
          principalCompanyArr.value = data;
        }
      } catch (err) {
        console.log(err);
      }
    };

    const initCommanyData = () => {
      getDeptData();
    };

    const searchCommanyData = (query = "") => {
      if (!query) {
        deptList.value = [];
        return;
      }
      getDeptData(query);
    };

    async function getDeptData(query = "") {
      try {
        const params = {
          pageNum: 1,
          pageSize: 100,
          nameLike: query
        };
        const { code, data } = await postSysCompanyList(params);
        if (code === 200) {
          deptList.value = data.list.map(item => {
            return { id: item.id, companyName: item.companyName || "" };
          });
        }
      } catch (err) {
        console.log(err);
      }
    }

    // 确认提交
    const handleSubmit = (isSubmit: boolean): void => {
      if (isSubmit) {
        if (props.mode === "view") {
          emit("emitClose", false);
          return;
        }
        formRef.value.validate(async (valid: any) => {
          if (valid) {
            // @ts-ignore   后端目前还是多角色配置，所以这里还是数组
            const copeFormdata = cloneDeep(state.formData);
            state.btnloading = true;
            try {
              if (props.mode === "add") {
                const { code, message } = await addUser(copeFormdata);
                requestSuccess(code, message, isSubmit);
              } else {
                delete copeFormdata.pageInfo;
                const { code, message } = await updateScienceUser(copeFormdata);
                requestSuccess(code, message, isSubmit);
              }
            } catch (err) {
              state.btnloading = false;
              console.log("提交失败", err);
            }
          }
          state.btnloading = false;
          return false;
        });
      } else {
        emit("emitClose", isSubmit);
        state.btnloading = false;
      }
    };

    // 请求结果统一处理
    const requestSuccess = (
      code: number,
      message: string,
      isSubmit: boolean
    ) => {
      if (code === 200) {
        NotifMessage.success(message);
        emit("emitClose", isSubmit);
      }
    };

    // 请求角色列表数据
    async function getRoleList() {
      const params = { pageSize: 0 };
      const { code, data } = await roleList(params);
      if (code === 200) {
        roleLists.value = data.list;
      }
    }

    onMounted(() => {
      initPrincipalCompanyList();

      // 清除表单验证
      formRef.value.clearValidate();
      getRoleList();
      initUserTypeList();
      initCommanyData();
      if (props.mode === "edit" || props.mode === "view") {
        getUserInfo(currentInfo.value.id);
      }
    });

    const getUserInfo = async userId => {
      try {
        const params = {
          id: userId
        };
        const { code, data } = await postScienceUserInfo(params);
        if (code === 200) {
          const copyCurrentInfo = cloneDeep(data);
          // copyCurrentInfo.phoneNum = copyCurrentInfo.phoneNum.replace(
          //   /(\d{3})\d{4}(\d{4})/,
          //   "$1****$2"
          // );
          state.formData = copyCurrentInfo;
          // 是否内部员工
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 人员类型
    const initUserTypeList = async () => {
      try {
        const params = {
          dicType: "rd_user_type"
        };
        const { code, data } = await postDictList(params);
        if (code === 200) {
          userTypeList.value = data;
        }
      } catch (err) {
        console.log(err);
      }
    };

    const querySearchAsync = async (queryString: string) => {
      try {
        const params = {
          pageNum: 1,
          pageSize: 200,
          name: queryString
        };
        const { code, data } = await getUsersForScience(params);
        console.log(data, "datas");
        if (code === 200) {
          const result = data.list.map(item => {
            return {
              value: item.name,
              id: item.id,
              email: item.email,
              name: item.name,
              userName: item.userName,
              phoneNum: item.phoneNum,
              companyName: item.deptName || ""
            };
          });
          userList.value = result;
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleSelect = item => {
      state.formData.userName = item.userName;
      state.formData.email = item.email;
      state.formData.name = item.value;
      state.formData.phoneNum = item.phoneNum;
      state.formData.companyName = item.companyName || "";
      state.formData.sex = item.sex;
      state.formData.userId = item.id;
      formRef.value.clearValidate();
    };

    return {
      ...toRefs(state),
      deptList,
      principalCompanyArr,
      roleLists,
      companyLists,
      userTypeList,
      userList,
      userTypeEnum,
      formRef,
      formRules,
      handleSelect,
      querySearchAsync,
      getUserInfo,
      handleSubmit,
      initCommanyData,
      searchCommanyData
    };
  }
});
</script>
